﻿CREATE FUNCTION [dbo].[Substring](
@text nvarchar(max),
@ldelimiter nvarchar(32) = '<',
@rdelimiter nvarchar(32) = '>'
)
RETURNS @Strings TABLE
(
id int IDENTITY PRIMARY KEY,
value nvarchar(max))
AS
BEGIN
	DECLARE @LINDEX int, @RINDEX int
	SET @LINDEX = CHARINDEX(@ldelimiter, @text)
	SET @RINDEX = CHARINDEX(@rdelimiter, @text)
  
	WHILE (@LINDEX > 0 AND @RINDEX > 0) 
	BEGIN
		IF (@LINDEX > 0 AND @RINDEX > 0)
		BEGIN
			DECLARE @leftTrim nvarchar(max), @value nvarchar(max)
			SET @leftTrim = LEFT(@text, @RINDEX - 1)
			SET @value = RIGHT(@leftTrim, (LEN(@leftTrim) - (@LINDEX + LEN(@ldelimiter) - 1)))
			
			SET @text = LEFT(@text, @LINDEX - 1) + RIGHT(@text, LEN(@text) - (@RINDEX + LEN(@rdelimiter) - 1))
			
			 INSERT INTO @Strings (value)
			 VALUES (@value)
		END
		SET @LINDEX = CHARINDEX(@ldelimiter, @text)
		SET @RINDEX = CHARINDEX(@rdelimiter, @text)
	END
	
  RETURN
END